let db = require('../db');

//部门数据拉取

exports.departmentList = async  function(start,length,name) {
 
   start = parseInt(start);
   length = parseInt(length);
   name='%'+name+'%'
   let sql=`
    SELECT SQL_CALC_FOUND_ROWS *,
    DATE_FORMAT(createdAt,'%Y-%m-%d %H:%i') AS createdAt
    FROM   department 
    `

    if(name){
        sql+=` where name like :name `
    }

    sql+=` limit :start,:length ;`
    sql += `   SELECT FOUND_ROWS() sum;`
    sql = sql.replace('AND', 'WHERE');

    let data = await db.query(sql,{start,length,name});
    return data[0];
}

//验证部门名称是否重复

exports.validationDepartment =  async function(name){
  let sql=`
   select *from department   where name =:name
  `  
  let  data = await db.query(sql,{name});
  return data[0];
}


//验证更改时部门名称是否重复
exports.validationEditDepartment  = async function (id,name){
    let sql=`
    select *from department   where name =:name and id!=:id
    `
    let data = await db.query(sql,{id,name});
    return data[0];
}

//添加部门

exports.addDepartment = async function(name,director,phone){
    let sql=`
     INSERT INTO department (name,director,phone)
     VALUES(:name,:director,:phone)
    `
    let data = await db.query(sql,{name,director,phone});
    return data[0];
}


//修改部门信息

exports.editDepartment = async function(id,name,director,phone){
    let sql=`
    UPDATE department set
    name=:name,
    director=:director,
    phone=:phone
    where id=:id
    `
    let data=  await db.query(sql,{id,name,director,phone});
    return data[0];
}

//删除部门

exports.delDepartment = async function(id){
    let sql=`
    delete  from department   where id =:id
    `
    let data = await db.query(sql,{id});
     return data[0];
}